package com.singlemountaintech.haogongjiang.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;
import android.util.Log;


import com.singlemountaintech.haogongjiang.qfd.SoleMountainApp;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StreamCorruptedException;

/**
 * Created by LUOLI on 2017/03/10.
 */
public class LoginUtil {
    private static SharedPreferences sp;

    public static void getSp(Context context) {
        if (sp == null) {
            sp = context.getSharedPreferences("user.info", Context.MODE_PRIVATE);
        }
    }

    /**
     * desc:保存对象
     *
     * @param context
     * @param key
     * @param obj     要保存的对象，只能保存实现了serializable的对象
     *                modified:
     */
    public static void saveUserInfo(Context context, String key, Object obj) {
        try {
            getSp(context);
            // 保存对象
            SharedPreferences.Editor sharedata = sp.edit();
            //先将序列化结果写到byte缓存中，其实就分配一个内存空间
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream os = new ObjectOutputStream(bos);
            //将对象序列化写入byte缓存
            os.writeObject(obj);
            //将序列化的数据转为16进制保存
            String bytesToHexString = bytesToHexString(bos.toByteArray());
            //保存该16进制数组
            sharedata.putString(key, bytesToHexString);
            sharedata.commit();
        } catch (IOException e) {
            e.printStackTrace();
            Log.e("", "保存obj失败");
        }
    }

    /**
     * desc:将数组转为16进制
     *
     * @param bArray
     * @return modified:
     */
    public static String bytesToHexString(byte[] bArray) {
        if (bArray == null) {
            return null;
        }
        if (bArray.length == 0) {
            return "";
        }
        StringBuffer sb = new StringBuffer(bArray.length);
        String sTemp;
        for (int i = 0; i < bArray.length; i++) {
            sTemp = Integer.toHexString(0xFF & bArray[i]);
            if (sTemp.length() < 2)
                sb.append(0);
            sb.append(sTemp.toUpperCase());
        }
        return sb.toString();
    }

    /**
     * desc:获取保存的Object对象
     *
     * @param context
     * @param key
     * @return modified:
     */
    public static Object readUserInfo(Context context, String key) {
        try {
            getSp(context);
            // 保存对象
            if (sp.contains(key)) {
                String string = sp.getString(key, "");
                if (TextUtils.isEmpty(string)) {
                    return null;
                } else {
                    //将16进制的数据转为数组，准备反序列化
                    byte[] stringToBytes = StringToBytes(string);
                    ByteArrayInputStream bis = new ByteArrayInputStream(stringToBytes);
                    ObjectInputStream is = new ObjectInputStream(bis);
                    //返回反序列化得到的对象
                    Object readObject = is.readObject();
                    return readObject;
                }
            }
        } catch (StreamCorruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //所有异常返回null
        return null;
    }

    /**
     * desc:将16进制的数据转为数组
     *
     * @param data
     * @return modified:
     */
    public static byte[] StringToBytes(String data) {
        String hexString = data.toUpperCase().trim();
        if (hexString.length() % 2 != 0) {
            return null;
        }
        byte[] retData = new byte[hexString.length() / 2];
        for (int i = 0; i < hexString.length(); i++) {
            int int_ch;  // 两位16进制数转化后的10进制数
            char hex_char1 = hexString.charAt(i); ////两位16进制数中的第一位(高位*16)
            int int_ch1;
            if (hex_char1 >= '0' && hex_char1 <= '9')
                int_ch1 = (hex_char1 - 48) * 16;   //// 0 的Ascll - 48
            else if (hex_char1 >= 'A' && hex_char1 <= 'F')
                int_ch1 = (hex_char1 - 55) * 16; //// A 的Ascll - 65
            else
                return null;
            i++;
            char hex_char2 = hexString.charAt(i); ///两位16进制数中的第二位(低位)
            int int_ch2;
            if (hex_char2 >= '0' && hex_char2 <= '9')
                int_ch2 = (hex_char2 - 48); //// 0 的Ascll - 48
            else if (hex_char2 >= 'A' && hex_char2 <= 'F')
                int_ch2 = hex_char2 - 55; //// A 的Ascll - 65
            else
                return null;
            int_ch = int_ch1 + int_ch2;
            retData[i / 2] = (byte) int_ch;//将转化后的数放入Byte里
        }
        return retData;
    }

    public static void putToken(String token) {
        getSp(SoleMountainApp.getInstance());
        sp.edit().putString("access_token", token).commit();
    }

    public static String getToken() {
        getSp(SoleMountainApp.getInstance());
        return sp.getString("access_token", "");
    }
    /**
     * 存取用户的刷新token
     *
     * @param token
     */
    public static void putRefreshToken(String token) {
        getSp(SoleMountainApp.getInstance());
        sp.edit().putString("refreshToken", token).commit();
    }

    public static String getRefreshToken() {
        getSp(SoleMountainApp.getInstance());
        return sp.getString("refreshToken", "");
    }
    public static void putUserId(String userId) {
        getSp(SoleMountainApp.getInstance());
        sp.edit().putString("UserId", userId).commit();
    }

    public static String getUserId() {
        getSp(SoleMountainApp.getInstance());
        return sp.getString("UserId", "");
    }

    /**
     * 身份证号
     */
    public static void setIdentityCode(String userId) {
        getSp(SoleMountainApp.getInstance());
        sp.edit().putString("IdentityCode", userId).commit();
    }

    public static String getIdentityCode() {
        getSp(SoleMountainApp.getInstance());
        return sp.getString("IdentityCode", "");
    }

    public static void putCookie(String cookie) {
        getSp(SoleMountainApp.getInstance());
        sp.edit().putString("Cookie", cookie).commit();
    }

    public static String getCookie() {
        getSp(SoleMountainApp.getInstance());
        return sp.getString("Cookie", "");
    }

    /**
     * 首页借款状态值
     *
     * @param applyStatus
     */
    public static void putApplyStatus(int applyStatus) {
        getSp(SoleMountainApp.getInstance());
        sp.edit().putInt("ApplyStatus", applyStatus).commit();
    }

    public static int getApplyStatus() {
        getSp(SoleMountainApp.getInstance());
        return sp.getInt("ApplyStatus", 0);
    }

    public static void putLoanId(String userId) {
        getSp(SoleMountainApp.getInstance());
        sp.edit().putString("LoanId", userId).commit();
    }

    public static String getLoanId() {
        getSp(SoleMountainApp.getInstance());
        return sp.getString("LoanId", "");
    }

    /*
     *  判断是否登录
     */
    public static void setLogin(Boolean login) {
        getSp(SoleMountainApp.getInstance());
        sp.edit().putBoolean("login", login).commit();
    }

    public static Boolean getLogin() {
        getSp(SoleMountainApp.getInstance());
        return sp.getBoolean("login", false);
    }

    /**
     * 判断是否登录
     */
    public static boolean isLogin() {
        boolean isLogin = getLogin();
        String token = getToken();
//        UserModelBean userModelBean = getUserModelBean();
//        if (userModelBean != null && !TextUtils.isEmpty(token) && isLogin ) {
//            return true;
//        }
        return false;
    }

 /*
      *    用于存放手势密码
      */

    public static void saveGesturePwd(String pwd) {
        getSp(SoleMountainApp.getInstance());
        sp.edit().putString("GesturePwd", pwd).commit();
    }

    /*
     *   获取 手势密码
     */
    public static String getGesturePwd() {
        getSp(SoleMountainApp.getInstance());
        return sp.getString("GesturePwd", "");
    }
     /*
      *    用于签到存放时间
      */

    public static void SaveSignTime(String time) {
        getSp(SoleMountainApp.getInstance());
        sp.edit().putString("SignTime", time).commit();
    }

    /*
     *   获取 签到时间
     */
    public static String getSignTime() {
        getSp(SoleMountainApp.getInstance());
        return sp.getString("SignTime", "");
    }

    /*
     *本地存放openid
     */
    public static void saveOpenid(String openid) {
        getSp(SoleMountainApp.getInstance());
        sp.edit().putString("openid", openid).commit();
    }

    public static String getOpenId() {
        getSp(SoleMountainApp.getInstance());
        return sp.getString("openid", null);
    }


//    public static String getUserPid() {
//        UserModelBean userModelBean = (UserModelBean) LoginUtil.readUserInfo(TanApp.getInstance(), USER_INFO);
//        return userModelBean == null ? String.valueOf(0) : userModelBean.getPid();
//    }

    //
//    public static UserModelBean getUserModelBean() {
//        return (UserModelBean) readUserInfo(TanApp.getInstance(), USER_INFO);
//    }

    /*
     *  控制 只是第一次 启动app  进入
     */
    public static void setFirstUsed(boolean bu) {
        getSp(SoleMountainApp.getInstance());
        sp.edit().putBoolean("goSplash", bu).commit();
    }

    public static boolean getFirstUsed() {
        getSp(SoleMountainApp.getInstance());
        return sp.getBoolean("goSplash", true);
    }

    /*
     *记录是否帮过银行卡
     */
    public static void setBindBankCard(boolean bu) {
        getSp(SoleMountainApp.getInstance());
        sp.edit().putBoolean("BindBankCard", bu).commit();
    }

    public static boolean getBindBankCard() {
        getSp(SoleMountainApp.getInstance());
        return sp.getBoolean("BindBankCard", false);
    }

    /*
         *记录是否设置过支付密码
         */
    public static void setIsSetPayPwd(boolean bu) {
        getSp(SoleMountainApp.getInstance());
        sp.edit().putBoolean("IsSetPayPwd", bu).commit();
    }

    public static boolean getIsSetPayPwd() {
        getSp(SoleMountainApp.getInstance());
        return sp.getBoolean("IsSetPayPwd", false);
    }

    /*
     *  存放和 读取用户密码 和手机号
     */
    public static void saveUserPwd(String pwd) {
        getSp(SoleMountainApp.getInstance());
        sp.edit().putString("pwd", pwd).commit();
    }

    public static String getUserPwd() {
        getSp(SoleMountainApp.getInstance());
        return sp.getString("pwd", "");
    }

    public static void saveUserPhone(String phone) {
        getSp(SoleMountainApp.getInstance());
        sp.edit().putString("phone", phone).commit();
    }

    public static String getUserPhone() {
        getSp(SoleMountainApp.getInstance());
        return sp.getString("phone", "");
    }

    /*
     *   记录是否是第一次 App
     */
    public static void setGoFirstApp(boolean first) {
        getSp(SoleMountainApp.getInstance());
        sp.edit().putBoolean("gofirst", first).commit();
    }

    public static boolean getGoFirstApp() {
        getSp(SoleMountainApp.getInstance());
        return sp.getBoolean("gofirst", false);
    }

    /*
     *  Fenglingyue 注：
     *   存储当前 用户等级
     */
    public static void saveGrade(int greed) {
        getSp(SoleMountainApp.getInstance());
        sp.edit().putInt("greed", greed).commit();
    }

    public static int getGrade() {
        getSp(SoleMountainApp.getInstance());
        return sp.getInt("greed", 666);
    }

    public static void saveIconCount(String count) {
        getSp(SoleMountainApp.getInstance());
        sp.edit().putString("count", count).commit();
    }

    public static String getIconCount() {
        getSp(SoleMountainApp.getInstance());
        return sp.getString("count", "5");
    }

    /**
     * 记录手势密码的开关
     */
    public static void setGestureToggle(boolean b) {
        getSp(SoleMountainApp.getInstance());
        sp.edit().putBoolean("GestureToggle", b).commit();
    }

    public static boolean getGestureToggle() {
        getSp(SoleMountainApp.getInstance());
        return sp.getBoolean("GestureToggle", false);
    }

    /**
     * 记录指纹密码的开关
     */
    public static void setFingerToggle(boolean b) {
        getSp(SoleMountainApp.getInstance());
        sp.edit().putBoolean("FingerToggle", b).commit();
    }

    public static boolean getFingerToggle() {
        getSp(SoleMountainApp.getInstance());
        return sp.getBoolean("FingerToggle", false);
    }


    /**
     * 保存身份证认证的信息
     */
    public static void setIdCard(String mRresult) {
        getSp(SoleMountainApp.getInstance());
        sp.edit().putString("mRresult", mRresult).commit();

    }

    public static String getIdCard() {
        getSp(SoleMountainApp.getInstance());
        return sp.getString("mRresult", "");
    }

    /**
     * 清除所有信息
     */
    public static void clearLoginMessAge() {
        setGestureToggle(false);
        setFingerToggle(false);
        setLogin(false);
        putToken("");//清除token  不然无法换账号获取验证码
        putRefreshToken("");//清除token  不然无法换账号获取验证码
        putUserId("");
        setImageUrl("");
        setIdentityCode("");
        setBindBankCard(false);
        setIsSetPayPwd(false);
    }

    /**
     * 清除token
     */
    public static void clearToken() {
        setLogin(false);
        putToken("");//清除token  不然无法换账号获取验证码
        putUserId("");
        setImageUrl("");
        setIdentityCode("");
        setBindBankCard(false);
        setIsSetPayPwd(false);
    }


    /**
     * 设置首页前借款是否弹出过可提现的提示框
     *
     * @param key
     * @param b
     */
    public static void setIsWithdraw(String key, boolean b) {
        getSp(SoleMountainApp.getInstance());
        sp.edit().putBoolean(key, b).commit();
    }

    public static boolean getIsWithdraw(String key) {
        getSp(SoleMountainApp.getInstance());
        return sp.getBoolean(key, false);
    }

    public static void setImageUrl(String file) {
        getSp(SoleMountainApp.getInstance());
        sp.edit().putString("File", file).commit();
    }

    public static String getImageUrl() {
        getSp(SoleMountainApp.getInstance());
        return sp.getString("File", "");
    }
}
